package com.djnt.catering;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.djnt.catering.QuickQueryStack.IQuery;
import com.djnt.catering.database.City;

public class CitySearchActivity extends Activity {

	private ListView city_search_listview;
	private AllCitiesAdapter mEfficientAdapter;
	catering mApp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.city_search);
		// getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
		// R.layout.custom_title_1);

		mApp = (catering) getApplication();

		city_search_listview = (ListView) this
				.findViewById(R.id.city_search_listview);
		Cursor c = getContentResolver().query(City.CONTENT_URI, null, null,
				null, null);
		startManagingCursor(c);
		mEfficientAdapter = new AllCitiesAdapter();
		city_search_listview.setAdapter(mEfficientAdapter);
		city_search_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int postion, long id) {
				// TODO Auto-generated method stub
				TextView i = (TextView) view;
				setResultForCityName(i.getText().toString());
			}
		});

		dispatchIntent();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);

		dispatchIntent();
	}

	private void dispatchIntent() {
		// TODO Auto-generated method stub
		// get and process search query here
		final Intent queryIntent = getIntent();
		final String queryAction = queryIntent.getAction();
		if (Intent.ACTION_SEARCH.equals(queryAction)) {
			doSearchQuery(queryIntent);
		}
	}

	protected void setResultForCityName(String t) {
		// TODO Auto-generated method stub
		Intent i = new Intent();
		i.putExtra(Settings.Persist.CITY_NAME, t);
		setResult(RESULT_OK, i);
		finish();
	}

	private void doSearchQuery(Intent queryIntent) {
		// TODO Auto-generated method stub
		// The search query is provided as an "extra" string in the query intent
		final String queryString = queryIntent
				.getStringExtra(SearchManager.QUERY);
		// mQueryText.setText(queryString);

		// Record the query string in the recent queries suggestions provider.
		SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
				SearchSuggestionSampleProvider.AUTHORITY,
				SearchSuggestionSampleProvider.MODE);
		suggestions.saveRecentQuery(queryString, null);

		// If your application provides context data for its searches,
		// you will receive it as an "extra" bundle in the query intent.
		// The bundle can contain any number of elements, using any number of
		// keys;
		// For this Api Demo we're just using a single string, stored using
		// "demo key".
		final Bundle appData = queryIntent
				.getBundleExtra(SearchManager.APP_DATA);
		if (appData == null) {
			// mAppDataText.setText("<no app data bundle>");
		}
		if (appData != null) {
			String testStr = appData.getString("demo_key");
			// mAppDataText.setText((testStr == null) ? "<no app data>" :
			// testStr);
		}

		// Report the method by which we were called.
		// mDeliveredByText.setText(entryPoint);
	}

	private class AllCitiesAdapter extends BaseAdapter implements IQuery {

		LayoutInflater mInflater;
		private QuickQueryStack mQuery;
		ArrayList<Integer> mData;
		private HashMap<String, Integer> province_map;
		private String[] cities_array;
		static final int SIZE_OF_CITY = 7;

		AllCitiesAdapter() {
			mInflater = LayoutInflater.from(CitySearchActivity.this);
			Resources res = getResources();
			String[] province_array = res
					.getStringArray(R.array.province_array);
			province_map = new HashMap<String, Integer>();
			int i;
			for (i = 0; i < province_array.length; i++) {
				province_map.put(province_array[i], i + 1);
			}
			cities_array = res.getStringArray(R.array.cities_array);
			int size = cities_array.length / SIZE_OF_CITY;
			mData = new ArrayList<Integer>(size);
			for (i = 0; i < size; i++) {
				mData.add(i);
			}
			mQuery = new QuickQueryStack(this, mData);
		}

		public int getCount() {
			return mQuery.getCount();
		}

		/**
		 * Since the data comes from an array, just returning the index is
		 * sufficent to get at the data. If we were using a more complex data
		 * structure, we would return whatever object represents one row in the
		 * list.
		 * 
		 * @see android.widget.ListAdapter#getItem(int)
		 */
		public Object getItem(int position) {
			return position;
		}

		/**
		 * Use the array index as a unique id.
		 * 
		 * @see android.widget.ListAdapter#getItemId(int)
		 */
		public long getItemId(int position) {
			return position;
		}

		/**
		 * Make a view to hold each row.
		 * 
		 * @see android.widget.ListAdapter#getView(int, android.view.View,
		 *      android.view.ViewGroup)
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			// A ViewHolder keeps references to children views to avoid
			// unneccessary calls
			// to findViewById() on each row.
			TextView i;

			// When convertView is not null, we can reuse it directly, there is
			// no need
			// to reinflate it. We only inflate a new View when the convertView
			// supplied
			// by ListView is null.
			if (convertView == null) {
				i = (TextView) mInflater.inflate(
						android.R.layout.simple_list_item_1, null);
			} else {
				i = (TextView) convertView;
			}

			// Bind the data efficiently with the holder.
			Integer index = (Integer) mQuery.getItemEntry(position);
			i.setText(cities_array[index * SIZE_OF_CITY + 1]);

			return i;
		}

		@Override
		public String[] getText(Object it) {
			// TODO Auto-generated method stub
			Integer index = (Integer) it;
			return new String[] { cities_array[index * SIZE_OF_CITY + 3] };
		}

	}

}
